<template>
    <el-autocomplete :style="{ width: '950px' }" v-model="state" :fetch-suggestions="querySearchAsync"
                     placeholder="请输入问题" @select="handleSelect" ref="automaticPromptRef"/>
  </template>
   
  <script lang="ts" setup>
  import { ref, watch, defineEmits ,defineExpose} from 'vue';
  import axios from 'axios';
  const state = ref('');
   
  interface LinkItem {
    value: string;
    link: string;
  }
   
  const links = ref<LinkItem[]>([]);
   
  const loadFromBackend = async (value: string) => {
    try {
  //输入时候请求后端根据输入值得到提示。    后端返回集合，集合里面对象属性为value和link都是string类型
      const response = await axios.get(`http://localhost:8080/getAutoMsg/${value}`);
      links.value = response.data;
    } catch (error) {
      console.error(error);
    }
  };
   
  const querySearchAsync = (queryString: string, cb: (arg: any) => void) => {
    const results = queryString ? links.value.filter(createFilter(queryString)) : links.value;
    cb(results);
  };
   
  const createFilter = (queryString: string) => {
    return (link: LinkItem) => {
      return link.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
    };
  };
   
  const handleSelect = (value: string) => {
   
  };
   
  const emit = defineEmits(['updateState']);
   
  watch(state, async (newValue) => {
    emit('updateState',newValue)
    if (newValue) {
      await loadFromBackend(newValue);
    } else {
      links.value = [];
    }
  });
   
  defineExpose({
    setState(res){
      state.value = res
    },
    getState(){
      return state.value
    }
  })
  </script>